package com.cqhgcloud.monarch.organ.util;

import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

/**
 * 响应信息主体
 */
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ApiModel(value = "响应信息主体")
public class R<T> implements Serializable {
	private static final long serialVersionUID = 1L;

	@Getter
	@Setter
	@ApiModelProperty(value = "返回标记：成功标记=0，失败标记=1")
	private int code;

	@Getter
	@Setter
	@ApiModelProperty(value = "返回信息")
	private String msg;


	@Getter
	@Setter
	@ApiModelProperty(value = "数据")
	private T data;

	public static <T> R<T> ok() {
		return restResult(null, CommonConstants.SUCCESS, null);
	}

	public static <T> R<T> ok(T data) {
		return restResult(data, CommonConstants.SUCCESS, null);
	}

	public static <T> R<T> ok(T data, String msg) {
		return restResult(data, CommonConstants.SUCCESS, msg);
	}

	public static <T> R<T> failed() {
		return restResult(null, CommonConstants.FAIL, null);
	}

	public static <T> R<T> failed(String msg) {
		return restResult(null, CommonConstants.FAIL, msg);
	}

	public static <T> R<T> failed(T data) {
		return restResult(data, CommonConstants.FAIL, null);
	}

	public static <T> R<T> failed(T data, String msg) {
		return restResult(data, CommonConstants.FAIL, msg);
	}

	private static <T> R<T> restResult(T data, int code, String msg) {
		R<T> apiResult = new R<>();
		apiResult.setCode(code);
		apiResult.setData(data);
		apiResult.setMsg(msg);
		return apiResult;
	}
/*
	public R(ResponseEnum responseEnum) {
		this.code = responseEnum.getCode();
		this.msg = responseEnum.getMessage();
	}

	public R(ResponseEnum responseEnum, T data) {
		this.code = responseEnum.getCode();
		this.msg = responseEnum.getMessage();
		this.data = data;
	}

	public static R error(ResponseEnum responseEnum) {
		return new R(responseEnum);
	}

	public static R error(ResponseEnum responseEnum, String msg) {
		return new R(responseEnum);
	}

	public static R error(BindingResult result, MessageSource messageSource) {
		StringBuffer msg = new StringBuffer();
		// 获取错误字段集合
		List<FieldError> fieldErrors = result.getFieldErrors();
		// 获取本地locale,zh_CN
		Locale currentLocale = LocaleContextHolder.getLocale();
		// 遍历错误字段获取错误消息
		for (FieldError fieldError : fieldErrors) {
			// 获取错误信息
			String errorMessage = messageSource.getMessage(fieldError, currentLocale);
			// 添加到错误消息集合内
			msg.append(fieldError.getField() + "：" + errorMessage + " , ");
		}
		return R.error(ResponseEnum.INCORRECT_PARAMS, msg.toString());
	}*/
}
